export class Layer {
	constructor(viewer) {
		this.viewer = viewer;
		this.layerList = [];
	}

	async get() {
		let layers = this.viewer.getStyle().layers;
		this.layerList = [...layers];
		layers = layers.map((layer, index) => {
			let opacity = '';
			switch (layer.type) {
				case 'symbol':
					opacity = this.viewer.getPaintProperty(layer.id, 'icon-opacity');
					break;
				case 'hillshade':
					opacity = 1;
					break;
				default:
					opacity = this.viewer.getPaintProperty(layer.id, `${layer.type}-opacity`);
			}
			return {
				id: layer.id,
				index: index,
				name: layer.id,
				type: layer.type,
				visibility: !(this.viewer.getLayoutProperty(layer.id, 'visibility') == 'none'),
				transparent: opacity ? opacity : 1
			};
		});
		return layers;
	}

	async show(ids) {
		const layers = this.find(ids);
		layers.forEach((layer) => {
			property && this.viewer.setLayoutProperty(layer.id, 'visibility', 'visible');
		});
	}

	async hide(ids) {
		const layers = this.find(ids);
		layers.forEach((layer) => {
			property && this.viewer.setLayoutProperty(layer.id, 'visibility', 'none');
		});
	}

	getLayerProperty(type, property) {
		switch (type) {
			case 'symbol':
				return `icon-${property}`;
			case 'hillshade':
				return undefined;
			default:
				return `${type}-${property}`;
		}
	}

	async transparent(ids, opacity = 0.6) {
		const layers = this.find(ids);
		layers.forEach((layer) => {
			let property = this.getLayerProperty(layer.type, 'opacity');
			property && this.viewer.setPaintProperty(layer.id, property, opacity);
		});
	}

	find(ids) {
		ids = Array.isArray(ids) ? ids : [ids];
		this.get();
		const result = ids.map((id) => this.layerList.filter((item) => item.id === id));
		return result.flat();
	}
}
